package com.ruiysoft.security.config;


import com.ruiysoft.security.handler.CustomOAuth2AccessDeniedHandler;
import com.ruiysoft.security.point.CustomAuthExceptionEntryPoint;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

import javax.annotation.Resource;

/**
 * Created by 化增光 on 2018/5/8.
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Resource
    CustomAuthExceptionEntryPoint customAuthExceptionEntryPoint;

    @Resource
    CustomOAuth2AccessDeniedHandler customOAuth2AccessDeniedHandler;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .antMatchers(
                        "/microprogram/payCallbackConfirm"
                        , "/microprogram/payRefundConfirm"
                        , "/logistics/callback/**"
                        , "/getLivePlayerUrl"
                        , "/getLivePushUrl"
                        ,"/gs-micro-websocket/**"
                        ,"/user/**/greeting/"
                        ,"/api/message/",
                        "/v2/api-docs",
                        "/configuration/ui",
                        "/swagger-resources",
                        "/configuration/security",
                        "/swagger-ui.html",
                        "/webjars/**",
                        "/swagger-resources/configuration/ui")
                .permitAll()
                .anyRequest().authenticated()
                .and().logout().permitAll()
                .and().formLogin().permitAll();
        //.and().addFilterBefore(new EntryGivenEnterpriseFilter(), AbstractPreAuthenticatedProcessingFilter.class)
//        EntryGivenEnterpriseFilter entryGivenEnterpriseFilter = new EntryGivenEnterpriseFilter("/oauth/token");
//        entryGivenEnterpriseFilter.setAuthenticationManager(authenticationManager);
        //http.addFilterBefore(new EntryGivenEnterpriseFilter(), AbstractPreAuthenticatedProcessingFilter.class);


    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.authenticationEntryPoint(customAuthExceptionEntryPoint)
                .accessDeniedHandler(customOAuth2AccessDeniedHandler);
    }
}
